<script setup lang="ts">
// 导入socket.io插件
import {io} from 'socket.io-client';
import type {Socket} from 'socket.io-client';
import RoomStatus from './components/RoomStatus.vue';
import RoomMessage from './components/RoomMessage.vue';
import RoomAction from './components/RoomAction.vue';
import { baseURL } from '@/utiles/request';
import { useUserStore } from '@/stores';
import { useRoute } from 'vue-router';
import { nextTick, onMounted, onUnmounted, ref } from 'vue';
import type { Message, TimeMessages } from '@/types/room';
import { MsgType,OrderType } from '@/types/enum';
import type { ConsultOrderItem } from '@/types/consult';
import { getConsultOrderDetail } from '@/api/consult';
import type { Image } from '@/types/consult'
import { provide } from 'vue'
// 控制子组件渲染
const isShow = ref(false)
/**
 * 初始化创建ws长连接(打电话)
 * 1.通过io函数传入后台ws链接地址和相关参数
 * 2.通过io实例的connect事件监听连接成功与否
 * 3.通过io实例的disconnect事件监听断开连接
 * 
 */
// 存储socket实例
const store =  useUserStore()
const route = useRoute()
let socket: Socket;
let list = ref<Message[]>([])
const initSocket = () => {
    socket = io(baseURL,{
        auth:{
            token: 'Bearer '+ store.user?.token
        },
        query:{
            orderId:route.query.orderId
        }
    })
    socket.on('connect',()=>{
        // console.log('连接成功');
    })
    // 说明{data}:{data添加类型}
    socket.on('chatMsgList',({data}:{data:TimeMessages[]})=>{
        // console.log('chatMsgList',data);
        const result:Message[] = []
        data.forEach((item)=>{
            // 1.发送消息的时间放入到result中
            result.push({
                id:item.createTime,
                msgType:MsgType.Notify,
                createTime:item.createTime,
                msg:{
                    content:item.createTime
                }
            })
            // 2.把items中的消息放入到result中
            result.push(...item.items)
            // 3.处理好的消息列表追加到list
            list.value.push(...result)
            // console.log('list',list.value);
            
        })
    })
    socket.on('error',()=>{
        // console.log('连接失败!出错了');
    })
    socket.on('disconnect',()=>{
        // console.log('断开连接');
    })
    // 接收消息
    socket.on('receiveChatMsg', async (msg) => {
    list.value.push(msg)
    await nextTick()
    window.scrollTo(0, document.body.scrollHeight)
  })
  // 接受订单变化消息
  socket.on('statusChange',()=>{
      getConsultDetail()
  })
 
}
// 获取订单详情
const consult = ref<ConsultOrderItem>()
const getConsultDetail = async () => {
    const res = await getConsultOrderDetail(route.query.orderId as string)
    let data = res.data
    consult.value = data
    console.log('consult',consult.value);
    isShow.value = true
    // console.log(consult.value.status);
}
onMounted(()=>{
    initSocket()
    getConsultDetail()
})
onUnmounted(()=>{
    socket.close()
})
// 聊天列表
const sendText = (text:string) => {
    // 发送消息:发送人、接收人、消息类型、消息内容
    console.log(text);
    
    socket.emit('sendChatMsg',{
        from:store.user?.id,// 发送人
        to:consult.value?.docInfo?.id, //接收人
        msgType:MsgType.MsgText,// 消息类型
        msg:{content:text} // 消息内容
    })
}

 // 图片聊天
 const sendImage = (img: Image) => {
    console.log(img);
  socket.emit('sendChatMsg', {
    from: store.user?.id,
    to: consult.value?.docInfo?.id,
    msgType: MsgType.MsgImage,
    msg: { picture: img }
  })
}

// 注入订单信息
provide('consult', consult)
// 成功后修改消息
const completeEva = (score: number) => {
  const item = list.value.find((item) => item.msgType === MsgType.CardEvaForm)
  if (item) {
    item.msg.evaluateDoc = { score }
    item.msgType = MsgType.CardEva
  }
}
provide('consult', consult)
provide('completeEva', completeEva)
</script>

<template>
  <div class="room-page">
    <cp-nav-bar title="医生问诊室" :fixed="true"></cp-nav-bar>
    <!--接诊状态组件 :未接诊、咨询中、已结束-->
    <room-status :status="consult?.status" :countdown="consult?.countdown" v-if="isShow" />
    <!--问诊聊天列表消息-->
    <div class="messageList">
        <RoomMessage :list="list"/>
    </div>
    
    <!--底部操作栏组件-->
    <RoomAction @send-text="sendText" :disabled="consult?.status !== OrderType.ConsultChat" v-if="isShow" @send-image="sendImage"/>
  
  </div>
</template>

<style lang="scss" scoped>
.room-page {
  padding-bottom: 60px;
  min-height: 100vh;
  box-sizing: border-box;
  background-color: var(--cp-bg);
  .van-pull-refresh {
    width: 100%;
    min-height: calc(100vh - 150px);
  }
}
.messageList{
    padding-top: 100px;
}
</style>
